﻿using System.Collections.Generic;

namespace MyHome.Configuration.ViewModel
{
    public class DictionaryEntryViewModel<TKey, TValue> : ViewModelBase.ViewModel where TValue : class where TKey : class
    {
        #region Key property

        private TKey iKey;

        public TKey Key
        {
            get
            {
                return iKey;
            }
            set
            {
                if (Key != value)
                {
                    if (!dictionary.ContainsKey(value))
                    {
                        if (dictionary.ContainsKey(Key))
                        {
                            dictionary.Remove(Key);
                        }
                        iKey = value;
                        dictionary[Key] = Value;
                    }
                    OnPropertyChanged("Key");
                }
            }
        }

        #endregion Key property

        #region Value property

        private TValue iValue;

        public TValue Value
        {
            get
            {
                return iValue;
            }
            set
            {
                if (Value != value)
                {
                    iValue = value;
                    dictionary[Key] = value;
                    OnPropertyChanged("Value");
                }
            }
        }

        #endregion Value property

        private readonly IDictionary<TKey, TValue> dictionary;

        public DictionaryEntryViewModel(KeyValuePair<TKey, TValue> model, IDictionary<TKey, TValue> dictionary)
        {
            this.dictionary = dictionary;
            iKey = model.Key;
            iValue = model.Value;
        }
    }
}